﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using CommonWFLibrary;
using System.IO;

namespace DeepTalkWF
{
    /// <summary>
    /// Delete some files on disk. Since it might take a while - do it
    /// as a long living activity!
    /// </summary>
    public partial class DeleteFiles : LongRunningActivityBase
    {
        public DeleteFiles()
        {
            InitializeComponent();
            TimesToRetry = 10;
        }

        /// <summary>
        /// Get/Set the directory to delete.
        /// </summary>
        public DirectoryInfo Directory
        {
            get { return (DirectoryInfo)GetValue(DirectoryProperty); }
            set { SetValue(DirectoryProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Directory.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DirectoryProperty =
            DependencyProperty.Register("Directory", typeof(DirectoryInfo), typeof(DeleteFiles), new PropertyMetadata(null));

        [Serializable]
        public class Args
        {
            public DirectoryInfo _info;
        }

        [LongRunningGatherArguments]
        public Args Gather()
        {
            Args r = new Args();
            r._info = Directory;
            return r;
        }

        [LongRunningMethod]
        public static void Run(Args a)
        {
            int count = 0;
            while (count < 10)
            {
                count = count + 1;
                if (a._info.Exists)
                {
                    try
                    {
                        a._info.Delete(true);
                        return;
                    }
                    catch
                    {
                    }

                    ///
                    /// Often a crash means someone is holding onto a directory or something like that.
                    /// 

                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
    }
}
